package mysql

import (
	"fmt"
	settings "sems/setting"

	"go.uber.org/zap"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var Conn *gorm.DB

func Init(cfg *settings.MySQLConfig) (err error) {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?parseTime=true&loc=Local", cfg.User, cfg.Password, cfg.Host, cfg.Port, cfg.DB)
	conn, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		fmt.Printf("err:%s\n", err)
		panic(err)
	}
	Conn = conn
	// 注册 GORM 回调函数以记录错误
	registerCallbacks(Conn)
	return
}

func Close() {
	db, err := Conn.DB()
	if err != nil {
		zap.L().Info("Database close connection", zap.Error(err))
		return
	}
	err = db.Close()
	if err != nil {
		zap.L().Info("Database close connection", zap.Error(err))
		return
	}
}

func registerCallbacks(db *gorm.DB) {
	// 注册回调函数
	err := db.Callback().Create().After("gorm:create").Register("log_create", logDBError)
	if err != nil {
		return
	}
	err = db.Callback().Update().After("gorm:update").Register("log_update", logDBError)
	if err != nil {
		return
	}
	err = db.Callback().Delete().After("gorm:delete").Register("log_delete", logDBError)
	if err != nil {
		return
	}
	err = db.Callback().Query().After("gorm:query").Register("log_query", logDBError)
	if err != nil {
		return
	}
	err = db.Callback().Row().After("gorm:row").Register("log_row", logDBError)
	if err != nil {
		return
	}
	err = db.Callback().Raw().After("gorm:raw").Register("log_raw", logDBError)
	if err != nil {
		return
	}
}

func logDBError(db *gorm.DB) {
	if db.Error != nil {
		zap.L().Info("Database close connection", zap.Error(db.Error))
		return
	}
}
